<template>
  <el-dialog :visible.sync="visible"
             :title="$t('oss.upload')"
             :close-on-click-modal="false"
             :close-on-press-escape="false">
     <el-form label-position="right" label-width="100px"  :model="form" :rules="rules">
       <el-form-item label="description"  prop="description">
         <el-input v-model="form.description" placeholder="Please enter a description"></el-input>
       </el-form-item>
     </el-form>
    <el-upload :action="url"
               :headers="headers"
               :file-list="fileList"
               drag
               :data="form"
               multiple
               :before-upload="beforeUploadHandle"
               :on-success="successHandle"
               class="text-center">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text"
           v-html="$t('upload.text')"></div>
      <div class="el-upload__tip"
           slot="tip">{{ $t('upload.tip', { 'format': 'jpg、png、gif、zip、xml' }) }}</div>
    </el-upload>
    
  </el-dialog>
</template>

<script>
import Cookies from 'js-cookie'
export default {
  data () {
    return {
      visible: false,
      url: '',
      headers: {},
      num: 0,
      fileList: [],
      form: {
      description: '' 
      },
      rules: {
        description: [
          { required: true, message: 'Please enter a description', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init () {
      this.visible = true
      this.url = `${window.SITE_CONFIG['apiURL']}/web/um/sys/oss/upload`
      this.headers={token: Cookies.get('token')}
      this.num = 0
      this.fileList = []
      this.form.description = '' 
    },
    beforeUploadHandle (file) {
      if (!this.form.description.trim()) {
        this.$message.error('Please enter a description')
        return false
      }
      console.log(file,"file");
      if (file.type !== 'text/javascript' && file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif' && file.type !== 'application/x-zip-compressed'&& file.type !== 'text/xml') {
        this.$message.error(this.$t('upload.tip', { 'format': 'jpg、png、gif、zip、xml' }))
        return false
      }
      this.num++
    },
    successHandle (res, file, fileList) {
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      this.fileList = fileList
      this.num--
      if (this.num === 0) {
        this.$message({
          message: this.$t('prompt.success'),
          type: 'success',
          duration: 500,
          onClose: () => {
            this.visible = false
            this.$emit('refreshDataList')
          }
        })
      }
    }
  }
}
</script>
